﻿using AutoMapper;
using MediatR;
using SCM.API.Write.Application.Command.Sale;
using SCM.API.Write.Application.Command.SaleRefund;
using SCM.Domain;
using SCM.ErrorCode;
using SCM.Infrastructure.Implement;
using SCM.Infrastructure.Interface;
using System.Security.Claims;

namespace SCM.API.Write.Application.Handler.SaleRefund
{
    public class UpdateSaleRefundHandler : IRequestHandler<UpdateSaleRefundCommand, APIResult<int>>
    {
        IMapper mapper;
        DatabaseContext db;
        ILogger<UpdateSaleRefundHandler> logger;
        private readonly IHttpContextAccessor _httpContextAccessor;
        public UpdateSaleRefundHandler(IMapper mapper, DatabaseContext db, ILogger<UpdateSaleRefundHandler> logger, IHttpContextAccessor httpContextAccessor)
        {
            this.mapper = mapper;
            this.db = db;
            this.logger = logger;
            _httpContextAccessor = httpContextAccessor;
        }

        public Task<APIResult<int>> Handle(UpdateSaleRefundCommand request, CancellationToken cancellationToken)
        {
            try
            {
                APIResult<int> result = new APIResult<int>();
                var res = db.SqlSugar.Queryable<SaleRefundModel>().Where(x => x.Id == request.Id).First();
                if (res == null)
                {
                    result.Code = APIEnum.Fail;
                    result.Msg = "退货记录不存在";
                    return Task.FromResult(result);
                }
                res = mapper.Map(request, res);


                //获取创建人id
                var userIdClaim = _httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
                if (!int.TryParse(userIdClaim, out int userId))
                {
                    result.Code = APIEnum.Fail;
                    result.Msg = "无法获取有效的用户ID";
                    return Task.FromResult(result);
                }
                res.UpdateName = userId;
                res.CreateTime = DateTime.Now;

                if (request.ProductId==null)
                {
                    result.Code = APIEnum.Fail;
                    result.Msg = "产品编号不能为空";
                    return Task.FromResult(result);
                }
                if (string.IsNullOrEmpty(request.SaleRefundNum))
                {
                    result.Code = APIEnum.Fail;
                    result.Msg = "退货单号不能为空";
                    return Task.FromResult(result);
                }

                var purchas = db.SqlSugar.Queryable<SaleRefundModel>().Where(c => c.SaleRefundNum == request.SaleRefundNum && !c.IsDel && c.Id != request.Id).Count();
                if (purchas > 0)
                {
                    logger.LogError("退货单号唯一");
                    result.Code = APIEnum.Fail;
                    result.Msg = "退货单号唯一";
                    return Task.FromResult(result);
                }
                if (request.State < 1 || request.State > 3)
                {
                    result.Code = APIEnum.Fail;
                    result.Msg = "状态值只能为1~3";
                    result.Data = 0;
                    return Task.FromResult(result);
                }
                int r = db.SqlSugar.Updateable(res).ExecuteCommand();
                if (r > 0)
                {
                    result.Msg = "修改销售退货单信息成功";
                    result.Data = r;
                    result.Code = APIEnum.Success;
                }
                else
                {
                    result.Msg = "修改销售退货单信息失败";
                    result.Data = r;
                    result.Code = APIEnum.Fail;
                }
                return Task.FromResult(result);
            }
            catch (Exception ex)
            {
                logger.LogError(ex.Message, "处理销售退货修改命令时发生异常");
                throw;
            }
        }
    }
}
